const router = require('koa-router')()
const USER = require('../models/users')
const JWT = require('jsonwebtoken')

router.get('/:id',async function (ctx, next) {
  ctx.body = await USER.find({id:ctx.params.id})
})

// 登录获取token
router.post('/login', async function (ctx, next) {
  let obj = ctx.request.body
  let user = await USER.findOne({$and:[{id:obj.id,password:obj.password}]})
  if(user){
    //存储1 ，秘钥，有效期
    let token = await JWT.sign({_id:user._id},'123456', { expiresIn: '7d' })
    ctx.body = {
      user:user,
      token:token
    }
  }else {
    ctx.body = '用户名或密码错误'
  }

})

// 注册
router.post('/sign',async function (ctx, next) {
  let obj = ctx.request.body
  let userNumber = await USER.find().count()
  if(obj.name){
    obj.id = 100000+userNumber
    ctx.body = await USER.create(obj)
  }else {
    ctx.body ='格式错误'
  }
})


module.exports = router
